#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void sigcallback(int signo)
{
    printf("signo:%d\n",signo);
    wait(NULL);
}

int main()
{
    //回调函数 父进程回收子进程 防止成为僵尸进程
    signal(SIGCHLD,sigcallback);
    //创建套接字
    int listen_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("socket");
        return 0;
    }
    //绑定地址信息
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(27878);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_sock,(struct sockaddr*)&addr,sizeof(addr));
    //监听
    ret =  listen(listen_sock,5);
    if(ret < 0)
    {
        perror("listen");
        return 0;
    }

    while(1)
    {
        //通过监听套接字获得新连接到套接字
        int new_sock = accept(listen_sock,NULL,NULL);
        //创建子进程
        int pid = fork();
        if(pid < 0)
        {
            perror("fork");
            return 0;
        }
        else if(pid == 0)
        {
            while(1)
            {

                //child
                close(listen_sock);
                //发送和接收
                char buf[1024] = {0};
                ssize_t recv_size = recv(new_sock,buf,sizeof(buf)-1,0);
                if(recv_size < 0)
                {
                    perror("recv");
                    return 0;
                }
                else if(recv_size == 0)
                {
                    printf("peer shutdown\n");
                    close(new_sock);
                    //子进程退出
                    exit(1);
                }
                printf("recv \"%s\"\n",buf);
                memset(buf,'\0',sizeof(buf));

                strcpy(buf,"i am server");
                send(new_sock,buf,sizeof(buf)-1,0);
            }
        }
        else 
        {
            //father
            close(new_sock);
        }
    }
    return 0;
}
